package lab.ddc.controller.admin;

import java.util.Date;

import lab.ddc.Util.MD5;
import lab.ddc.Util.Modelext;
import lab.ddc.model.User;

import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;

@ControllerBind(controllerKey="/admin/user",viewPath="/admin")
public class UserController extends Controller {
	
	private static final Modelext modelext = new Modelext("用户","user");
	
	public void index(){
		int page = 1;
        if (getParaToInt()!=null){
            page = getParaToInt();
        }
		setAttr("modelext", modelext);
        setAttr("page", User.dao.paginate(page, 15, "select * ", "from user"));
        render("model.ftl");
	}
	
	public void addform(){
		setAttr("modelext", modelext);
		render("model_add.ftl");
	}
	
	public void add(){
		User user = getModel(User.class);
		user.set("password", MD5.getMD5(user.getStr("password")));
		user.set("created", new Date());
		user.save();
		redirect("/admin/user");
	}
	
	public void updateform(){
		setAttr("modelext", modelext);
		setAttr("user", User.dao.findById(getParaToInt()));
		render("model_update.ftl");
	}
	
	public void update(){
		User user = getModel(User.class);
		if(!User.dao.findById(user.getLong("id")).getStr("password").equals(user.getStr("password")))
			user.set("password", MD5.getMD5(user.getStr("password")));
		user.update();
		redirect("/admin/user");
	}
	
	public void delete(){
		User user = User.dao.findById(getParaToInt());
		user.delete();
		redirect("/admin/user");
	}
	
}
